/*
 * ServerTask.cpp
 *
 *  Created on: 03.12.2012
 *      Author: zheka
 */

#include "ServerTask.hpp"
#include "util/Log.hpp"
#include "util/StringUtils.hpp"
#include "ReadClientRequestTask.hpp"
#include "Task.hpp"
#include "pthread/Thread.hpp"
#include "io/ClientThread.hpp"
ServerTask::ServerTask(Server & server, TaskThreadPool * pool) :
		Task(server.getSocketFileDescriptor()), server(server), pool(pool) {

}

void ServerTask::onInit(Context & context) {
	context.enableRead();
	Log::v("Registered task");
}

void ServerTask::onRead(Context & context) {
	Log::v("accept");
	int clientSocket = server.accept();

#if defined(MULTITHREAD_VERSION_2)

	TaskThread * thread = pool->getTaskThread();
	Log::v("[TRY] accepted thread = "+StringUtils::toString((int)thread));
	thread->addTask(new ReadClientRequest(clientSocket));
	Log::v("[OK] accepted thread = "+StringUtils::toString((int)thread));
#elif defined(MULTITHREAD_VERSION_1)

	Log::v("Start new thread");
	try {
		Thread * thread = new ClientThread(clientSocket);
		thread->start();
	} catch(...) {
		close(clientSocket);
	}
#else

	context.registerNewTask(new ReadClientRequest(clientSocket));
#endif
}
